using System;
using ArticleManagementSystem.Api.Entity;
using ArticleManagementSystem.Api.Params;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using ArticleManagementSystem.Api.Utils;

namespace ArticleManagementSystem.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    // token
    public class AuthenticationController : ControllerBase
    {
        private TokenParameter _tokenParameter = new TokenParameter();
        private IConfiguration _iconfiguration;
        public AuthenticationController(IConfiguration iconfiguration)
        {
           _iconfiguration = iconfiguration;

            _tokenParameter =_iconfiguration.GetSection("TokenParameter").Get<TokenParameter>();
        }


        [HttpPost, Route("requestToken")]
        public ActionResult RequestToken([FromBody] Users request)
        {
            //生成Token和RefreshToken
            var token = TokenHelper.GenUserToken(_tokenParameter, request.Username);
            var refreshToken = "123456";
            return Ok(new[] { token, refreshToken });
        }
        
        //刷新token
        [HttpPost,Route("refreshToken")]
        public dynamic RefreshToken(RefreshTokenDTO refresh)
        {
            var username=TokenHelper.ValidateToken(_tokenParameter,refresh);
            if(string.IsNullOrEmpty(username)){
                return new
                {
                    HashCode=104,
                    Data="",
                    Msg="token验证失败"
                };
            }
            var token=TokenHelper.GenUserToken(_tokenParameter,username);
            var refreshToken="123456";

            return new
            {
                Code=200,
                Data=new{token=token,refreshToken=refreshToken},
                Msg="刷新token成功"
            };
        }
    }
}